package com.shen.JUC.duilie;

import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

public class Test {
    public static void main(String[] args) throws InterruptedException {
        test4();
    }

    //抛出异常
    public static void test1() {
        //队列大小
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(2);
        System.out.println(blockingQueue.add("a"));
        System.out.println(blockingQueue.add("b"));

        System.out.println(blockingQueue.remove());//移除首位元素
        System.out.println(blockingQueue.element());//查看队首元素
    }

    //不抛出异常,返回false
    public static void test2() {
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(2);
        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        //移除失败，返回null
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.peek());
    }

    //阻塞，一直等待
    public static void test3() throws InterruptedException {
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(2);
        blockingQueue.put("a");
        blockingQueue.put("b");

        System.out.println(blockingQueue.take());

    }

    //阻塞，等待超时
    public static void test4() throws InterruptedException {
        ArrayBlockingQueue blockingQueue = new ArrayBlockingQueue<>(2);
        System.out.println(blockingQueue.offer("a"));
        System.out.println(blockingQueue.offer("b"));
        blockingQueue.offer("c", 2, TimeUnit.SECONDS);//等待超过2秒直接退出
        System.out.println("线程阻塞");
        System.out.println(blockingQueue.poll());
        System.out.println(blockingQueue.poll());
        blockingQueue.poll(2,TimeUnit.SECONDS);
        System.out.println("线程结束");

    }
}
